import base64,pickle
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request,user,response):
    """
    合并请求用户的购物车数据，将未登录保存在cookie里的保存到redis中
    遇到cookie与redis中出现相同的商品时以cookie数据为主，覆盖redis中的数据
    :param request: 用户的请求对象
    :param user: 当前登录的用户
    :param response: 响应对象，用于清楚购物车cookie
    :return:
    """
    # 未登录的购物车覆盖登录的购物车，
    # 如果登录的购物车某样商品在未登录中的购物车也有，
    # 那就按照未登录的商品选未选中状态和数量来显示在登录后的购物车
    cart = request.COOKIES.get('cart_cookie')

    if cart:
        cart_cookie = pickle.loads(base64.b64decode(cart.encode()))
    else:
        return response

    cart = {}

    redis_cart_selected_add = []

    redis_cart_selected_remove = []

    for sku_id,count_selected_dict in cart_cookie.items():
        # 处理商品数量
        cart[sku_id] = count_selected_dict['count']

        if count_selected_dict['selected']:
            redis_cart_selected_add.append(sku_id)
        else:
            redis_cart_selected_remove.append(sku_id)

    # cart有值才删除未选中的sku_id和添加选中的sku_id
    if cart:
        conn = get_redis_connection('cart')
        pl = conn.pipeline()
        pl.hmset('carts_%s' % user.id,cart)
        if redis_cart_selected_add:
            pl.sadd('carts_selected_%s' % user.id,*redis_cart_selected_add)
        if redis_cart_selected_remove:
            pl.srem('carts_selected_%s' % user.id,*redis_cart_selected_remove)
        pl.execute()

    response.delete_cookie('cart_cookie')
    return response